package com.picshare.controller;

import com.picshare.config.ServerConfig;
import com.picshare.model.ApiKey;
import com.picshare.model.User;
import com.picshare.service.ApiService;
import com.picshare.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ApiService apiService;
    
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username, 
                       @RequestParam String password, 
                       HttpSession session, 
                       Model model) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
    
    @GetMapping("/settings")
    public String settingsPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 获取服务器配置
        ServerConfig serverConfig = ServerConfig.getInstance();
        model.addAttribute("user", user);
        model.addAttribute("serverIp", serverConfig.getServerIp());
        model.addAttribute("serverPort", serverConfig.getServerPort());
        
        return "settings";
    }
    
    @PostMapping("/settings/change-password")
    public String changePassword(@RequestParam String oldPassword,
                               @RequestParam String newPassword,
                               @RequestParam String confirmPassword,
                               HttpSession session,
                               Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("error", "新密码确认不匹配");
            // 重新获取服务器配置
            ServerConfig serverConfig = ServerConfig.getInstance();
            model.addAttribute("user", user);
            model.addAttribute("serverIp", serverConfig.getServerIp());
            model.addAttribute("serverPort", serverConfig.getServerPort());
            return "settings";
        }
        
        if (userService.changePassword(user.getUsername(), oldPassword, newPassword)) {
            session.invalidate();
            return "redirect:/login?changed=true";
        } else {
            model.addAttribute("error", "原密码错误");
            // 重新获取服务器配置
            ServerConfig serverConfig = ServerConfig.getInstance();
            model.addAttribute("user", user);
            model.addAttribute("serverIp", serverConfig.getServerIp());
            model.addAttribute("serverPort", serverConfig.getServerPort());
            return "settings";
        }
    }
    
    @PostMapping("/settings/update-server")
    public String updateServerConfig(@RequestParam String serverIp,
                                    @RequestParam int serverPort,
                                    HttpSession session,
                                    Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 验证输入
        if (serverIp == null || serverIp.trim().isEmpty()) {
            model.addAttribute("error", "服务器IP地址不能为空");
            model.addAttribute("user", user);
            model.addAttribute("serverIp", serverIp);
            model.addAttribute("serverPort", serverPort);
            return "settings";
        }
        
        if (serverPort < 1 || serverPort > 65535) {
            model.addAttribute("error", "服务器端口必须在1-65535之间");
            model.addAttribute("user", user);
            model.addAttribute("serverIp", serverIp);
            model.addAttribute("serverPort", serverPort);
            return "settings";
        }
        
        // 更新服务器配置
        try {
            ServerConfig serverConfig = ServerConfig.getInstance();
            serverConfig.setServerIp(serverIp.trim());
            serverConfig.setServerPort(serverPort);
            serverConfig.saveConfig();
            
            model.addAttribute("success", "服务器配置更新成功");
        } catch (Exception e) {
            model.addAttribute("error", "服务器配置更新失败: " + e.getMessage());
        }
        
        model.addAttribute("user", user);
        model.addAttribute("serverIp", serverIp);
        model.addAttribute("serverPort", serverPort);
        return "settings";
    }
    
    // API Key管理接口
    
    @PostMapping("/settings/api/generate")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateApiKey(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 检查是否已有API Key
            List<ApiKey> existingKeys = apiService.getUserApiKeys(user.getUsername());
            if (!existingKeys.isEmpty()) {
                result.put("success", false);
                result.put("message", "您已有一个API Key，请先删除现有的Key");
                return ResponseEntity.ok(result);
            }
            
            // 生成新的API Key
            ApiKey apiKey = apiService.createApiKey(user.getUsername(), "客户端API Key");
            
            result.put("success", true);
            result.put("apiKey", apiKey.getKey());
            result.put("message", "API Key生成成功");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成API Key失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @PostMapping("/settings/api/delete")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteApiKey(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 获取用户的API Key
            List<ApiKey> userKeys = apiService.getUserApiKeys(user.getUsername());
            if (userKeys.isEmpty()) {
                result.put("success", false);
                result.put("message", "没有找到API Key");
                return ResponseEntity.ok(result);
            }
            
            // 删除API Key
            boolean deleted = apiService.deleteApiKey(userKeys.get(0).getKey());
            if (deleted) {
                result.put("success", true);
                result.put("message", "API Key删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除API Key失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除API Key失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @GetMapping("/settings/api/status")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getApiKeyStatus(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            List<ApiKey> userKeys = apiService.getUserApiKeys(user.getUsername());
            if (userKeys.isEmpty()) {
                result.put("hasApiKey", false);
                result.put("message", "暂无API Key");
            } else {
                ApiKey apiKey = userKeys.get(0);
                result.put("hasApiKey", true);
                result.put("apiKey", apiKey.getKey());
                result.put("created", apiKey.getCreatedAt());
                result.put("active", apiKey.isActive());
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }
}